//
//  HNAPayWebView.m
//  HNAPayMobileSDK
//
//  Created by Ly_work on 15/11/18.
//  Copyright © 2015年 usolv. All rights reserved.
//

#import "HNAPayWebView.h"
#import "HNAPayDefaultDefine.h"
#import "FRMS.h"

static void (^__loadedBlock)(UIWebView *webView);
static void (^__failureBlock)(UIWebView *webView, NSError *error);
static void (^__loadStartedBlock)(UIWebView *webView);
static BOOL (^__shouldLoadBlock)(UIWebView *webView, NSURLRequest *request, UIWebViewNavigationType navigationType);
/**
 Set TRUE_END_REPORT to YES to get notified only when the page has *fully* loaded, and not when every single element loads. (still not fully tested). When this is set to NO, it will work exactly like the UIWebViewDelegate. (Default behavior)
 */
#define TRUE_END_REPORT NO

static uint __loadedWebItems;

@interface HNAPayWebView ()<UIWebViewDelegate,UIScrollViewDelegate>

@property (nonatomic, strong) UIProgressView *progressView;
@property (nonatomic, strong) NSTimer *fakeProgressTimer;

@end

@implementation HNAPayWebView

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
        [self.progressView setTrackTintColor:[UIColor colorWithWhite:1.0f alpha:0.0f]];
        [self.progressView setFrame:CGRectMake(0, 20, frame.size.width, self.progressView.frame.size.height)];
        [self.progressView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
        [self addSubview:self.progressView];
        self.delegate = (id)self;
    }
    return self;
}
+(nullable HNAPayWebView *)  hnaPayWebViewWithFrame:(CGRect)frameR
                                        loadRequest:(NSURLRequest *)request
                                             loaded:(void (^)(UIWebView * _Nonnull))loadedBlock
                                             failed:(void (^)(UIWebView * _Nonnull, NSError * _Nonnull))failureBlock
                                        loadStarted:(void (^)(UIWebView * _Nonnull))loadStartedBlock
                                         shouldLoad:(BOOL (^)(UIWebView * _Nonnull, NSURLRequest * _Nonnull, UIWebViewNavigationType))shouldLoadBlock{
    
    __loadedWebItems    = 0;
    
    __loadedBlock       = loadedBlock;
    __failureBlock      = failureBlock;
    __loadStartedBlock  = loadStartedBlock;
    __shouldLoadBlock   = shouldLoadBlock;
    
    HNAPayWebView *webView  = [[HNAPayWebView alloc] initWithFrame:frameR];
    //    webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    //    webView.multipleTouchEnabled = YES;
    //    webView.autoresizesSubviews = YES;
    //    webView.scalesPageToFit = YES;
    webView.scrollView.bounces = NO;
    webView.scrollView.alwaysBounceVertical = NO;
    webView.scrollView.alwaysBounceHorizontal = NO;
    webView.scrollView.backgroundColor = [UIColor blackColor];
    //    webView.keyboardDisplayRequiresUserAction = NO;
    
//    [webView removeAllCache];

    /*
     
    ******不使用SDK获取设备指纹，完全采用js获取******
     
    //配置cooKie参数
    NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
    NSString *fingerPrint = [[NSUserDefaults standardUserDefaults] objectForKey:@"fingerPrint"];
    if (fingerPrint != nil && ![fingerPrint  isEqual: @""]) {
//        [cookieProperties setObject:fingerPrint forKey:NSHTTPCookieValue];
//        [cookieProperties setObject:[request.URL host] forKey:NSHTTPCookieDomain];
//        [cookieProperties setObject:[request.URL path] forKey:NSHTTPCookiePath];
//        [cookieProperties setObject:@"fingerPrint" forKey:NSHTTPCookieName];
//        [cookieProperties setObject:[request.URL absoluteString] forKey:NSHTTPCookieOriginURL];
        [cookieProperties setObject:@"BSFIT_DEVICEID" forKey:NSHTTPCookieName];
        [cookieProperties setObject:fingerPrint forKey:NSHTTPCookieValue];
        [cookieProperties setObject:@".hnapay.com" forKey:NSHTTPCookieDomain];
        [cookieProperties setObject:@".hnapay.com" forKey:NSHTTPCookieOriginURL];
        [cookieProperties setObject:@"/" forKey:NSHTTPCookiePath];
//        [cookieProperties setObject:@"0" forKey:NSHTTPCookieVersion];
//        [cookieProperties setObject:[NSDate dateWithTimeIntervalSinceNow:60*60*24] forKey:NSHTTPCookieExpires];//设置失效时间
//        [cookieProperties setObject:@"0" forKey:NSHTTPCookieDiscard]; //设置sessionOnly
        
        NSHTTPCookie *cookieuser = [NSHTTPCookie cookieWithProperties:[cookieProperties copy]];
//        [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyNever];
        [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookieuser];
        NSLog(@"（配置cooKie）cookies===%@",[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]);
    }
     
     */
    [webView loadRequest: request];
    
    return webView;
}
-(void)removeAllCache
{
    NSHTTPCookie *cookie;
    NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
//    NSLog(@"（removeAllCache）cookies===%@",[storage cookies]);
    for (cookie in [storage cookies])
    {
        [storage deleteCookie:cookie];
    }
    NSURLCache * cache = [NSURLCache sharedURLCache];
    [cache removeAllCachedResponses];
    [cache setDiskCapacity:0];
    [cache setMemoryCapacity:0];
}
-(void)isShowProgressView:(BOOL)isShow{
    self.progressView.hidden = !isShow;
}
#pragma mark UIWebViewDelegate

- (BOOL)webView:(HNAPayWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    if(__shouldLoadBlock)
        [self fakeProgressViewStartLoading];
    return __shouldLoadBlock(webView, request, navigationType);
    
    return YES;
}
- (void)webViewDidStartLoad:(HNAPayWebView *)webView
{
    __loadedWebItems++;
    
    if(__loadStartedBlock && (!TRUE_END_REPORT || __loadedWebItems > 0))
        __loadStartedBlock(webView);
}
- (void)webViewDidFinishLoad:(HNAPayWebView *)webView
{
    __loadedWebItems--;
    
    if(__loadedBlock && (!TRUE_END_REPORT || __loadedWebItems == 0)){
        [self fakeProgressBarStopLoading];
        __loadedWebItems = 0;
        __loadedBlock(webView);
    }
}
- (void)webView:(HNAPayWebView *)webView didFailLoadWithError:(NSError *)error
{
    __loadedWebItems--;
    
    if(__failureBlock)
        [self fakeProgressBarStopLoading];
    __failureBlock(webView, error);
}

#pragma mark - Fake Progress Bar Control (UIWebView)

- (void)fakeProgressViewStartLoading {
    [self.progressView setProgress:0.0f animated:NO];
    [self.progressView setAlpha:1.0f];
    
    if(!self.fakeProgressTimer) {
        self.fakeProgressTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f/60.0f target:self selector:@selector(fakeProgressTimerDidFire:) userInfo:nil repeats:YES];
    }
}

- (void)fakeProgressBarStopLoading {
    if(self.fakeProgressTimer) {
        [self.fakeProgressTimer invalidate];
    }
    
    if(self.progressView) {
        [self.progressView setProgress:1.0f animated:YES];
        [UIView animateWithDuration:0.3f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
            [self.progressView setAlpha:0.0f];
        } completion:^(BOOL finished) {
            [self.progressView setProgress:0.0f animated:NO];
        }];
    }
}

- (void)fakeProgressTimerDidFire:(id)sender {
    CGFloat increment = 0.005/(self.progressView.progress + 0.2);
    if([self isLoading]) {
        CGFloat progress = (self.progressView.progress < 0.75f) ? self.progressView.progress + increment : self.progressView.progress + 0.0005;
        if(self.progressView.progress < 0.95) {
            [self.progressView setProgress:progress animated:YES];
        }
    }
}

#pragma mark - private
- (void)setCookie {
    NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
    [cookieProperties setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"TraceId"] forKey:NSHTTPCookieName];
    NSHTTPCookie *cookieuser = [NSHTTPCookie cookieWithProperties:cookieProperties];
    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookieuser];
}
@end
